package com.spit.fammo.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.spit.amoeba.base.MyBaseViewModel
import com.spit.fammo.R
import com.spit.fammo.bean.DataBean
import com.spit.fammo.ext.STOCK_TAKE_LIST_PAGE
import com.spit.fammo.network.apiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.requestNoCheck

/**
 * User: Nike
 *  2025/1/10 14:09
 */
class UploadModel : MyBaseViewModel() {

    var listBean: MutableLiveData<ArrayList<DataBean>> = MutableLiveData()

    var uploadStockTakeSuccess: MutableLiveData<Pair<Int, Int>> = MutableLiveData()

    fun onRequest() {
        viewModelScope.launch(Dispatchers.IO) {
            var list = ArrayList<DataBean>()
            uploadOrderDao.findAll(userId).forEach {parentBean ->
                var childList = ArrayList<DataBean>()
                uploadOrderListDao.findAll().forEach {
                    childList.add(DataBean(userid = userId, Type = parentBean.type, name = it.name, orderId = it.orderId,
                    data = it.data))
                }
                list.add(DataBean(name = parentBean.name, userid = parentBean.userId, Type = parentBean.type, Status = parentBean.status,
                    expandableChild = childList))
            }
            listBean.postValue(list)
        }
    }

    fun uploadStockTake(bean: DataBean, groupPosition: Int, childPosition: Int) {
        requestNoCheck({apiService.uploadStockTake(bean.data)},{
            if (it.Status == 1){
                viewModelScope.launch(Dispatchers.IO) {
                    uploadOrderListDao.deleteById(bean.orderId)
                    var findAll = uploadOrderListDao.findTypeAll(STOCK_TAKE_LIST_PAGE)
                    if (findAll.size == 0){
                        uploadOrderDao.deleteById(STOCK_TAKE_LIST_PAGE)
                    }
                    uploadStockTakeSuccess.postValue(Pair(groupPosition, childPosition))
                }
            }
            ToastUtils.showShort(if (it.Status == 1) appContext.getText(R.string.upload_success) else appContext.getText(R.string.upload_fail))
        },{
            //请求失败 网络异常回调在这里
            loadingChange.dismissDialog
            ToastUtils.showShort(it.throwable!!.message)
            LogUtils.e(it.throwable, it.throwable!!.message)
        }, true, loadingMessage = "")
    }

    fun allUpload(listDrawBean: java.util.ArrayList<DataBean>) {
        listDrawBean.forEachIndexed { groupIndex, groupBean ->
            when(groupBean.Type){
                STOCK_TAKE_LIST_PAGE ->{
                    groupBean.expandableChild.forEachIndexed { index, bean ->
                        uploadStockTake(bean, groupIndex, index)
                    }
                }
            }
        }
    }

}